package com.shadow.demo.shiro.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.shadow.demo.data.shiro.entity.RolePermission;
import com.shadow.demo.data.shiro.mapper.RolePermissionMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class RolePermissionService extends BaseService<RolePermissionMapper, RolePermission>
        implements IService<RolePermission> {

    private RolePermissionService rolePermissionService;

    RolePermissionService(
            @Lazy RolePermissionService rolePermissionService
    ) {
        this.rolePermissionService = rolePermissionService;
    }

    /**
     * 配置角色的权限
     *
     * @param roleId 角色id
     * @param permissionList 权限列表
     * */
    public void configRole(final String roleId, final List<String> permissionList) {
        if (StringUtils.isEmpty(roleId)) {
            log.info("角色为空无法配置");
            throw new IllegalArgumentException();
        }
        LambdaQueryWrapper<RolePermission> wrapper = new LambdaQueryWrapper<RolePermission>()
                .in(RolePermission::getRoleId, roleId);
        remove(wrapper);
        wrapper.clear();
        if (CollectionUtils.isNotEmpty(permissionList)) {
            List<RolePermission> collect = permissionList.stream()
                    .map(x -> new RolePermission(roleId, x))
                    .collect(Collectors.toList());
            rolePermissionService.saveBatch(collect);
        }
    }
}
